package bdz.framework.web.controller
{
	
	import bdz.common.events.XMLLoaderEvent;
	import bdz.common.model.XMLLoader;
	import bdz.framework.web.model.BDZWFData;
	
	import com.adobe.crypto.SHA1;
	
	import flash.events.EventDispatcher;
	
	public class BDZWFGateway extends EventDispatcher
	{
		private static var instance:BDZWFGateway;
		private static var configuration:BDZWFConfig;
		private static var datamodel:BDZWFData;
		
		public function BDZWFGateway(se:SingletonEnforcer)
		{
			super();
			
		}
		private function createXMLLoader(event:String, success:Function):XMLLoader{
			var xm:XMLLoader = new XMLLoader(event);
			xm.addEventListener(event, success);
			xm.addEventListener(XMLLoaderEvent.FAULT, onDataFault);
			xm.location = configuration.baseURL+configuration.api;
			xm.contentType = "application/octet-stream";
			return xm;
		}
		private function onLoginSuccessful(evt:XMLLoaderEvent):void{
			datamodel.assignUser(new XML(evt.data));
			
		}
		private function onDataFault(evt:XMLLoaderEvent):void{
			
		}
		public static function getInstance(cfg:BDZWFConfig = null):BDZWFGateway{
			if(instance == null){
				instance = new BDZWFGateway(new SingletonEnforcer());
				configuration = cfg;
				instance.initializeComponent();
			}
			return instance;
		}
		private function initializeComponent():void{
			datamodel = BDZWFData.getInstance();
		}
		private function getAllTemplates():void{
			var xloader:XMLLoader = createXMLLoader("onTemplatesReceived", onTemplatesReceived);
			var tosend:XML = <df_templates/>;
			tosend.@method = "templates.get.all";
			tosend
		}
		private function onTemplatesReceived(evt:XMLLoaderEvent):void{
			
		}
		public function login(uname:String, pword:String):void{
			var xloader:XMLLoader = createXMLLoader("onLoginSuccess", onLoginSuccessful);
			var tosend:XML = <df_user/>;
			tosend.@method = "user.login";
			tosend.username = uname;
			tosend.password = SHA1.hash(pword);
			xloader.sendCompressed(tosend.toString());
		}
		
		
		

	}
}
/**
 * @private
 * 
 */
internal class SingletonEnforcer{}